import styles from './index.less';
import React, { useState, useEffect } from 'react';
import { history, connect } from 'umi';
import { ImuneTreeArr } from '@/types/common';
import { getMuneTree } from './servers';
import { getUrl } from '@/utils/common';
import { Layout, Menu } from 'antd';
const { Sider } = Layout;
import * as Icon from '@ant-design/icons';
import actions from '@/shared/actions';

const Index = (props: any) => {
  const { common } = props;

  // 左侧菜单数据
  const [menuTreeList, setMenuTreeList] = useState<ImuneTreeArr[]>([]);

  useEffect(() => {
    getMuneTreeFn();
  }, []);

  // 查询当前应用所拥有的菜单数据
  const getMuneTreeFn = async () => {
    const res = await getMuneTree({ url: getUrl() });
    setMenuTreeList(res?.data[0]?.muneTreeArr);

    res.data[0]?.muneTreeArr.forEach((item: ImuneTreeArr, index: number) => {
      if (item.path === history.location.pathname) {
        props.dispatch({
          type: 'common/save',
          payload: {
            menubar: [item],
            numberZindex: common.menubar.length,
            defaultSelected: [`${index + 1}`],
            menuTreeList: res?.data[0]?.muneTreeArr,
          },
        });
      }
    });
  };

  /**
   * 页面导航
   * @param item 菜单数据对象
   * @param index 选中项下标索引
   */
  const navLink = (item: ImuneTreeArr, index: number) => {
    const { path } = item;

    // 查询当前项在数组里的位置
    const Zindex = common.menubar.findIndex((item2: ImuneTreeArr) => item2.id === item.id);

    // 判断是否已有页签
    if (!common.menubar.includes(item)) {
      props.dispatch({
        type: 'common/save',
        payload: {
          menubar: [...common.menubar, item],
          numberZindex: common.menubar.length,
          defaultSelected: [`${index + 1}`]
        },
      });
    }
    // 有的情况下更改选中状态
    else {
      props.dispatch({
        type: 'common/save',
        payload: {
          numberZindex: Zindex,
          defaultSelected: [`${index + 1}`],
        },
      });
    }
    actions.setGlobalState({
      // 当前路径
      activePath: '',
    });
    history.push(path);
  };

  // 动态加载图标
  const iconFn = (iconString: any) => {
    return React.createElement(Icon[iconString], {
      style: { fontSize: '16px' },
    });
  };

  return (
    <div className={styles.sliderBox}>
      <Sider breakpoint="lg" collapsedWidth="0">
        <Menu theme="dark" mode="inline" selectedKeys={common.defaultSelected}>
          {menuTreeList?.map((item: ImuneTreeArr, index: number) => {
            return (
              <Menu.Item
                key={item.id}
                icon={iconFn('UserOutlined')}
                onClick={navLink.bind(this, item, index)}
              >
                {item.title}
              </Menu.Item>
            );
          })}
        </Menu>
      </Sider>
    </div>
  );
};

export default connect(({ common }: any) => ({ common }))(Index);
